<template>
<el-container>
  <el-header class="pdbt rigtop">
    <i class="fa el-icon-s-unfold" @click="clickFold" v-if="iconIf"></i> <i class="fa el-icon-s-fold" @click="clickFold" v-if="!iconIf"></i>区域内审核公式信息
  </el-header>
    <!-- <el-header class="height_auto pdbt" style="text-align: center">区域内审核公式信息</el-header> -->
    <el-main class="padding_top heiauto">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="90px" label-position="right">
        <el-form-item label="公式类型" prop="field102" class="items_margin">
          <el-radio-group v-model="formData.field102" size="mini">
            <el-radio v-for="(item, index) in field102Options" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效性" prop="field103" class="items_margin">
          <el-radio-group v-model="formData.field103" size="mini">
            <el-radio v-for="(item, index) in field103Options" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="校验类型" prop="field101" class="items_margin">
          <el-radio-group v-model="formData.field101" size="mini" @change="agreeChange">
            <el-radio v-for="(item, index) in field101Options" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="padding-bottom :10px">
          <el-container>
            <el-dropdown>
              <el-button type="primary" size="mini" class="special_btn">
                添加单元格<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" v-if="!!field196Options && field196Options.length > 0">
                <template v-for="item in field196Options">
                    <el-dropdown-item @click.native="loadExcel(item.tsCd)">{{ item.tsNm }}</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
            
            <!-- <el-aside width="60px">
               
            </el-aside> -->
            <el-container>
              <el-main>
                <el-row type="flex" justify="start" align="bottom" class="el_row_btn">
                  <el-form-item label-width="5px" label="" prop="field159">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="czfClick(' + ')"></el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field158">
                    <el-button type="primary" icon="el-icon-minus" size="mini" @click="czfClick(' - ')"></el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field156">
                    <el-button type="primary" icon="el-icon-close" size="mini" @click="czfClick(' * ')"></el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field164">
                    <el-button type="primary" size="mini" @click="czfClick(' / ')">÷</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field165">
                    <el-button type="primary" size="mini" @click="czfClick(' ( ')">（</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field166">
                    <el-button type="primary" size="mini" @click="czfClick(' ) ')">）</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field167">
                    <el-button type="primary" size="mini" @click="czfClick(' { ')">{</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field168">
                    <el-button type="primary" size="mini" @click="czfClick(' } ')">}</el-button>
                  </el-form-item>
                </el-row>
                <el-row type="flex" justify="start" align="bottom" class="el_row_btn">
                  <el-form-item label-width="5px" label="" prop="field170">
                    <el-button type="primary" size="mini" @click="czfClick(' && ')">&</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field171">
                    <el-button type="primary" size="mini" @click="czfClick(' || ')">||</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field172">
                    <el-button type="primary" size="mini" @click="czfClick(' > ')">></el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field173">
                    <el-button type="primary" size="mini" @click="czfClick(' >= ')">>=</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field174">
                    <el-button type="primary" size="mini" @click="czfClick(' == ')">==</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field175">
                    <el-button type="primary" size="mini" @click="czfClick(' < ')">＜</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field176">
                    <el-button type="primary" size="mini" @click="czfClick(' <= ')">＜＝</el-button>
                  </el-form-item>
                  <el-form-item label-width="5px" label="" prop="field177">
                    <el-button type="primary" size="mini" @click="czfClick(' != ')">!=</el-button>
                  </el-form-item>
                </el-row>
              </el-main>
            </el-container>
          </el-container>
        </div>
        
        <!-- <el-form-item label="添加单元格" prop="field196">
          <el-select v-model="tsCd" placeholder="选择索引表" clearable :style="{width: '100%'}" @change="loadExcel">
            <el-option v-for="(item, index) in field196Options" :key="index" :label="item.tsNm"
              :value="item.tsCd" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item> -->
        <el-table v-if="tableShow" size="mini" border style="width:100%; margin-bottom:5px;line-height:20px;font-size:12px;font-color:black" :data="tableData" :row-style="{height: '40px'}" :cell-style="{padding: '0'}">
          <el-table-column  label="表" width="100" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tsCd" type="text" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="有效范围" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.frang" type="text" size="mini"></el-input>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label-width="1px" label="" prop="field178">
            <el-input ref="m_input" v-model="inputOne" type="textarea" placeholder="请输入表内审核公式······"
            :autosize="{minRows: 10, maxRows: 1000}" :style="{width: '100%'}" @input="inputOneChange"></el-input>
        </el-form-item>
        <el-form-item label-width="1px" label="" prop="field179">
            <el-input ref="n_input" v-model="inputTwo" type="textarea" placeholder="请输入审核解释······"
            :autosize="{minRows: 7, maxRows: 1000}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        </el-form>
      </el-main>
    <el-footer style="text-align: center;">
       <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
        <!-- <el-button size="small" @click="clearForm">重置</el-button> -->
    </el-footer>
    <vxe-modal  v-model="addFl" v-if="addFl" title="选中单元格" width="1000px" height="950px" size="small" destroy-on-close>
          <div ref="sheetmain" class="bk_full_wapper"></div>
      </vxe-modal>
  </el-container>
</template>
<script>
  import request from "@/utils/requestutil";
  import {getRealUrl, syncRequest} from "@/utils/httpRequet";
  import $ from "jquery";
  import treeExhide from "@/components/ztree/lib/jquery.ztree.exhide.min.js";
  import dicPanel from '@/hr/utils/dicPanel'
  import { options } from 'runjs';
  import psTree from '@/components/psTree/psTree';
  import { isNull } from 'xe-utils/methods';
  import functionSelector from '@/components/FunctionSelector/FunctionSelector'
  import xspreadsheet from "@/components/x-spreadsheet/xspreadsheet.js";
  import "@/components/x-spreadsheet/xspreadsheet.css";
export default {
  components: {
    psTree,
    dicPanel,
    functionSelector,
  },
  props: [],
  data() {
    return {
      tableShow:true,
      tableData:[],
      iconIf: false,
      bzcode:"",
      ttId:"",
      tsCd:"",
      tsUn:"",//管理单位
      strType:"add",
      proofid:"",
      isDblclick:"",
      addFl:false,
      status:"add",//默认为添加
      inputOne:"",
      inputTwo:"",
      formData: {
        field102: 'MC',
        field103: '1',
        field101:'COL',
      },
      rules: {
        field102: [],
        field103: [],
        field196: [],
        field178: [],
        field179: [],
        field101: [{
          required: true,
          message: '校验类型不能为空',
          trigger: 'change'
        }],
      },
      field102Options: [{
        "label": "合理性",
        "value": 'RC'
      }, {
        "label": "强制性",
        "value": 'MC'
      }],
      field103Options: [{
        "label": "有效",
        "value": '1'
      }, {
        "label": "无效",
        "value": '0'
      }],
      field101Options: [{
        "label": "行校验",
        "value": 'ROW'
      }, {
        "label": "列校验",
        "value": 'COL'
      }, {
        "label": "其他",
        "value": 'OTHER'
      }],
      field196Options: [],
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    clickFold() {
      if(this.isFold==='1'){
        this.isFold = '0'
        this.iconIf = false
      }else{
        this.isFold = '1'
        this.iconIf = true
      }
      this.isFoldz = this.isFold
      this.$emit('myclickFoldQY', this.isFoldz)
    },
    submitForm() {
      // this.$refs['elForm'].validate(valid => {
      //   if (!valid) return
      //   // TODO 提交表单
      // })
      //this.formData.field101
      let _that = this;
      let prUn = _that.$store.state.user.userInfo.deptId;//获取管理单位
      let ft = _that.formData.field102;
      let fValid = _that.formData.field103;
      let fd = _that.formData.field101;
      let strTableList = _that.tableData;
      let frang = "";
      let tsCd = "";
      //判断有效范围长度是否一致
      if(strTableList.length > 1){
        for(var i = 1;i<strTableList.length;i++){
          let frangOne = strTableList[i].frang.split(",");
          let frangTwo = strTableList[i-1].frang.split(",");
          if(frangOne.length != frangTwo.length){
            _that.$message.warning("有效范围的长度不一致，请核对有效范围！");
            return false;
          }
        }
      }
      if(strTableList.length > 0){
        for(var i = 0;i<strTableList.length;i++){
          tsCd+= strTableList[i].tsCd+",";
          let frangVal = strTableList[i].frang.replace(/\s*/g,"");
          if(frangVal == "" || isNull(frangVal)){
            _that.$message.warning("有效范围不能为空!");
            return false;
          }
          frang += "{\"tsCd\":\""+strTableList[i].tsCd+"\",\"frang\":\""+strTableList[i].frang+"\"},"
        }
        frang = frang.substring(0,frang.length-1);
        tsCd = tsCd.substring(0,tsCd.length-1);
      }else{
        _that.$message.warning("公式范围不能为空！");
        return false;
      }
      let formula = _that.$refs.m_input.$refs.textarea.value;
      let fDesc = _that.$refs.n_input.$refs.textarea.value
      request({
        url:"bjshQYSaveData",
        method:"post",
        params:{ft:ft,fValid:fValid,fd:fd,frang:frang,formula:formula,fDesc:fDesc,bzcode:_that.bzcode,ttId:_that.ttId,tsCd:tsCd,prUn:prUn,strType:_that.strType,proofid:_that.proofid},
      }).then((data)=>{
        _that.$emit("qygridrefh",_that.bzcode,_that.ttId);
        if(data.data.success){
          if(_that.strType == "add"){
            _that.$message.success("新增成功！");
            _that.$emit("refreshData");
          }else{
            _that.$message.success("修改成功！");
            _that.$emit("refreshData");
          }
        }else{
          if(_that.strType == "add"){
            _that.$message.error("新增失败！");
          }else{
            _that.$message.error("修改失败！");
          }
        }
      })
    },
    resetForm() {
      this.strType="add";
      this.$refs['elForm'].resetFields();
      this.$refs.m_input.$refs.textarea.value = "";
      this.$refs.n_input.$refs.textarea.value = "";
      this.tableData = [];
    },
    clearForm(){
      this.$refs['elForm'].resetFields()
    },
    //加载（添加单元格）下拉框
    dygSelectData(bzcode,ttId){
      this.bzcode = bzcode;
      this.ttId = ttId;
      request({
        url:"bjshListSelect",
        method:"post",
        params:{bzcode:bzcode,ttid:ttId},
      }).then((data)=>{
        this.field196Options = data.data;
      })
    },
    loadExcel(val){
      let $t = this;
      $t.formData.field196 = val;
      $t.tsCd = val;
      $t.tsUn = $t.$store.state.user.userInfo.deptId;//获取管理单位
      this.addFl = true;
      this.$nextTick(function () {
        //初始化表单
        const option = {
          mode:'read',
          showToolbar: false,
          showZeroNumber: false,
          showGrid:false,
          height: $t.$refs.sheetmain.clientHeight,
          width: $t.$refs.sheetmain.clientWidth,
        };
        $t.workbook =new x_spreadsheet($t.$refs.sheetmain, option);
        $t.workbook.loadData([{
          rows: { len: 20 },
          clos: { len: 10 },
          name: "sheet1",
        }]);
        //绑定Excel的双击事件
        $t.workbook.on("cell-dblclick",function(){
          //根据X、Y坐标查询该位置的区域
          if(arguments < 3){
            $t.$message.warning("未获取到对应单元格坐标，请刷新或联系管理员");
            return false;
          }
          let x = arguments[1];
          let y = arguments[2]
          request({
            url:"bjshQYGetAreaCd",
            method:"post",
            params:{bzcode:$t.bzcode,ttId:$t.ttId,tsCd:$t.tsCd,tsUn:$t.tsUn,x:x,y:y},
          }).then((data)=>{
            let areaNm = "0";
            if(data.data.length > 0){
              areaNm = data.data.areaNm;
            }else{
              areaNm="0";
            }
            if($t.isDblclick == "1"){
              $t.$message.warning("该表没有配置模板,无法添加选择的单元格！");
              return false;
            }
            //根据选择的单元格动态添加table行
            let myField = $t.$refs.m_input.$refs.textarea.value;
            if(myField.indexOf($t.tsCd) == -1){
              $t.tableData.push({
              	"tsCd":$t.tsCd,
              	"frang":"",					
              });
            }
            let strAll = " @"+$t.tsCd+"@"+areaNm+"@"+x+"@"+y+" ";
            $t.czfClick(strAll);
          })
        })
      });
      request({//查询模板json
        url:"bjshQYExcelJson",
        method:"post",
        params:{bzcode:$t.bzcode,ttId:$t.ttId,tsCd:$t.tsCd,tsUn:$t.tsUn}
      }).then((data)=>{
        if(data.data == undefined || isNull(data.data)){
          $t.isDblclick = "1"
          $t.$message.warning("该表没有配置模板,请先配置末班再添加审核公式！");
          return false;
        }
        else{
          $t.isDblclick = "2"
        }
        if(data.data.length>0){
          $t.workbook.loadData(eval(data.data[0].tsTemp));
        }else{
          $t.$message.warning("该表没有配置模板,请刷新或者联系管理员！");
          return false;
        }
      })
    },
    czfClick(strNum){//用于追加或插入计算符号或要审核字段名称
      const myField = this.$refs.m_input.$refs.textarea;
      if (myField.selectionStart || myField.selectionStart === 0) {
        let startPos = myField.selectionStart;
        let endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + strNum + myField.value.substring(endPos, myField.value.length);
        myField.focus();
        myField.selectionStart = startPos + strNum.length;
        myField.selectionEnd = startPos + strNum.length;
      } else {
        this.inputOne += strNum
      }
    },
    //校验类型点击事件
    agreeChange(){
      if(this.formData.field101=="OTHER"){
        this.tableShow=false
        this.$refs.m_input.$refs.textarea.value = "";
      }else{
        this.tableShow=true;
        this.tableData=[];
      }
    },
    //回显数据
    setData(val){
      this.strType=val.type;//是修改update还是新增add
      this.bzcode= val.val.bzcode;
      this.ttId = val.val.ttId;
      this.proofid = val.val.proofid;
      this.formData.field102 = val.val.ft;
      this.formData.field103 = val.val.fValid;
      this.formData.field101 = val.val.fd;
      if(val.val.fd == "OTHER"){//会显示如果为其他校验类型，隐藏el-table
        this.tableShow=false;
      }else{
        this.tableShow=true;
      }
      this.$refs.m_input.$refs.textarea.value = val.val.formula;
      this.$refs.n_input.$refs.textarea.value = val.val.formula;
      if(val.val.frang != ""){
        let frang = JSON.parse(val.val.frang)
        if(val.val.fd !="OTHER"){
          this.tableData=[];
          if(frang.length > 0){
            for(var i = 0;i<frang.length;i++){
              this.tableData.push({
                "tsCd":frang[i].tsCd,
                "frang":frang[i].frang,					
              });
            }
          }
        }     
      }
    },
    //审核公式内容改变事件
    inputOneChange(){
      let tableDataList = this.tableData;
      let inputVal = this.$refs.m_input.$refs.textarea.value;
      inputVal = inputVal.replace(/^\s*|\s*$/g,"");
      if(inputVal.indexOf('@') != -1){
        for(var i=0;i<tableDataList.length;i++){
          if(inputVal.indexOf(tableDataList[i].tsCd) == -1){
            this.tableData.splice(i,1);
          }
        }
      }else{
        this.tableData = undefined;
      }
    },
    setIsFold(){
      this.isFold = '1'
      this.iconIf = true
      this.isFoldz = this.isFold
      this.$emit('myclickFoldQY', this.isFoldz)
    },
  }
}

</script>
<style lang="scss" scoped>
.padding_top .el-form{
  padding: 0 10px;
}
.padding_top{
  max-height:calc(100vh - 200px);
}

.el_row_btn .el-button--mini{
  padding:4px 5px;
  width:100%;
}
.padding_top .el_row_btn .el-form-item{
  margin-bottom: 0px;
  flex: 1;
  margin-top:0;
}
.padding_top .el-form-item{
  margin-top: 6px;
  margin-bottom: 6px;
}
.padding_top .el-textarea{
  margin-top: 8px;
  margin-bottom: 8px;
}
::v-deep .padding_top .el-form-item--medium .el-form-item__content{ text-align: left;
  line-height: 30px;
}

// .bk_box_wapper .bk_mid_wapper .section .el-header.pdbt{
//   padding-top:0;
//   padding-bottom: 0;
//   background:#f6f6f6;
// }
.el-header.pdbt{
  position: relative;
}
.pdbt .fa{
  position: absolute;
    left: 10px;
    top: 50%;
    margin-top: -7px;
    cursor: pointer;
}
.padding_top .el-radio{
  margin-right:13px;
}
.padding_top ::v-deep .el-radio__label{
  padding-left:4px;
}
.padding_top .items_margin{
  margin-left: -4px;
  margin-right: -10px;
}
.special_btn{
  padding:0;
  margin-top: 5px;
}
.special_btn ::v-deep span{
  width: 34px;
    display: inline-block;
    height: auto;
    white-space: normal;
    text-align: center;
    padding: 2px 4px;
    line-height: 15px;
}
.special_btn ::v-deep .el-icon--right{
  margin-left:0;
}
</style>
